import 'dart:convert';
import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:wanxiang_app/bean/merchant_entity.dart';
import 'package:wanxiang_app/pages/home/detail.dart';
import 'package:wanxiang_app/pages/home/search.dart';
import 'package:wanxiang_app/pages/home/searchResult.dart';
import 'package:wanxiang_app/pages/sell/sell.dart';
import 'package:wanxiang_app/pages/sell/sell2.dart';
import 'package:wanxiang_app/widgets/myappbar.dart';

import 'package:responsive_grid_list/responsive_grid_list.dart';

import '../../bean/game_list_entity.dart';
import '../../utils/common.dart';
import '../../utils/constant.dart';
import '../../utils/network_manager.dart';
import '../../utils/network_url.dart';
import '../../utils/tabChangeEvent.dart';
import '../../utils/toast_util.dart';
import '../../widgets/buy_merchant_dialog.dart';
import '../../widgets/pinyin.dart';
import 'package:lpinyin/lpinyin.dart';
import 'package:cached_network_image/cached_network_image.dart';

import '../login/login.dart';
import '../login/login_code.dart';
import 'buyResult.dart';

class SortController extends GetxController {
  @override
  void onInit() {
    super.onInit();
    Map map = {'type': '', 'name': '全部'};
    Map map2 = {'type': 'duanyou', 'name': '端游'};
    Map map3 = {'type': 'shouyou', 'name': '手游'};
    typeList.add(map);
    typeList.add(map2);
    typeList.add(map3);
    _getGameListData();
  }

  @override
  void onClose() {
    super.onClose();
  }

  List<String> pinyin = [
    '全部',
    'A',
    'B',
    'C',
    'D',
    'E',
    'F',
    'G',
    'H',
    'I',
    'J',
    'K',
    'L',
    'M',
    'N',
    'O',
    'P',
    'Q',
    'R',
    'S',
    'T',
    'U',
    'V',
    'W',
    'X',
    'Y',
    'Z'
  ];
  String pinyinClick = '全部';
  String type = '';
  List<Map> typeList = [];
  List<GameListData> list = [];
  List<GameListData> tempList = [];
  bool isFromIndex = false;
  _clickPinyin(word){
    pinyinClick = word;
    if(word == '全部'){
      _filter(type);
    }else{
      _filter(type);
      List<GameListData> aa = [];
      for(var item in tempList){
        if(word==  PinyinHelper.getFirstWordPinyin(item.name).substring(0,1).toUpperCase()){
          aa.add(item);
        }
      }
      tempList =aa;
      update();
    }
  }

  _filter(ttype) {
    type = ttype;
    if (type == '') {
      tempList = list;
    } else {
      tempList = [];
      for (var item in list) {
        if (item.type == type) {
          tempList.add(item);
        }
      }
    }

    update();
  }

  void _getGameListData() {
    Map map = {
      "top": '0',
    };
    DioManager.getInstance().post(ServiceUrl.gameList, map, (data) async {
      GameListEntity bannerEntity = GameListEntity.fromJson(jsonDecode(data));
      list = bannerEntity.data;
      tempList = list;
      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }
}

class HotPage extends GetView<SortController> {
  late SortController controller;
  late BuildContext context;
  String tags = '';
  HotPage(String tag1){
    tags = tag1;
  }
  @override
  Widget build(BuildContext context1) {
    Get.lazyPut<SortController>(() => SortController());
    controller = Get.find();
    context = context1;
    if(Get.arguments==null){
      controller.isFromIndex = true;
    }else{
      controller.isFromIndex = false;
    }
    return GetBuilder<SortController>(
      builder: (_) {
        return Scaffold(
            extendBodyBehindAppBar: true,
            body: _content());
      },
    );
  }

  Widget _top() {
    return
         Container(
            margin: EdgeInsets.only(left: 16.w, right: 25.w),
            height: 32.h,
            alignment: Alignment.topCenter,
            child: Row(
              children: [
                controller.isFromIndex?
                Image.asset(
                  '${Constant.IMG_BASE}logo.png',
                  width: 50.w,
                  height: 19.h,
                ):

                Image.asset(
                  '${Constant.IMG_BASE}ic_back.png',
                  width: 15.w,
                  height: 15.h,
                ),
                SizedBox(
                  width: 17.w,
                ),
                Expanded(
                      flex: 1,
                      child: InkWell(
                          onTap: (){
                            Get.to(()=>SearchPage(),preventDuplicates:false);
                          },
    child: Container(
      height: 32.h,
      decoration: BoxDecoration(
          color: Color(0xFFF5F5F5),
          borderRadius: BorderRadius.circular(17.r)),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          SizedBox(
            width: 18.w,
          ),
          Image.asset(
            'assets/images/home_search.png',
            width: 14.w,
            height: 14.h,
          ),
          SizedBox(
            width: 8.w,
          ),
          Text(
            '请输入游戏名称',
            style: TextStyle(
                color: Color(0xFF8B8B8B), fontSize: 13.sp),
          )
        ],
      ),
    )
    ) )
            ,
                SizedBox(
                  width: 21.w,
                ),

                InkWell(
                  onTap: () {
                    print('InkWellInkWellInkWellInkWell');
                    bool islogin = Common.checkLogin();
                    if (islogin) {
                      tabbarEventBus.fire(TabChangedEvent(400));
                    } else {
                      ToastUtil.show("请先登录");
                      Get.to(() => LoginCodePage(), preventDuplicates: false);
                    }
                  },
                  child: Image.asset(
                    'assets/images/home_service.png',
                    width: 24.w,
                    height: 22.h,
                  ),
                )

              ],
            ));
  }

  List<Widget> _tabs() {
    List<Widget> aa = [];
    for (var item in controller.typeList) {
      aa.add(_tabItem(item));
    }
    return aa;
  }

  Widget _tabItem(item) {
    return InkWell(
        onTap: () {
          controller._filter(item['type']);
        },
        child: Container(
          width: (MediaQuery.of(context).size.width - 20.w) / 3,
          height: 28.h,
          child: Column(
            children: [
              Text(item['name']),
              SizedBox(
                height: 5.h,
              ),
              controller.type == item['type']
                  ? Container(
                      height: 1.5.h,
                      color: const Color(0xFF007BE5),
                    )
                  : Container(
                      height: 1.5.h,
                    )
            ],
          ),
        ));
  }

  List<Widget> _pinyinAll() {
    List<Widget> aa = [];
    for (var item in controller.pinyin) {
      aa.add(_pinyinItem(item));
    }
    return aa;
  }

  Widget _pinyinItem(item) {
    return InkWell(
        onTap: () {
          controller._clickPinyin(item);
        },
        child: Container(
            margin: EdgeInsets.only(right: 3.w),
            child: Text(
              item,
              style: controller.pinyinClick ==item? TextStyle(fontSize: 12.sp,color:Color(0xFF007BE5) ):TextStyle(fontSize: 12.sp),
            )));
  }

  Widget _content() {
    return Container(
        child: Stack(children: [
      Container(
          child: Column(
        children: [
          SizedBox(
            height: MediaQueryData.fromWindow(window).padding.top + 21.h,
          ),
          _top(),
          Container(
            height: 10.h,
            color: Color(0xfff2f3f5),
            margin: EdgeInsets.only(top: 10.h),
          ),
          SizedBox(
            height: 10.h,
          ),
          Container(
              margin: EdgeInsets.only(left: 10.w, right: 10.w),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: _tabs(),
              )),
          SizedBox(height: 15.h,),
          Container(
              color: Color(0xfff2f3f5),
              height: 20.h,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: _pinyinAll(),
              )),
          Expanded(
              child: Container(
                  margin: EdgeInsets.only(left: 10.w, right: 10.w),
                  child: _hotList())),
          // SizedBox(height: 20.h,),
        ],
      )),
      // IndexBar(key:ValueKey('pinyin'),top:100,indexBarCallBack: (content) {
      // })
    ]));
  }

  Widget _hotList() {
    return Container(
        alignment: Alignment.center,
        child: GridView.count(
          crossAxisCount: 4,
          crossAxisSpacing: 9.w,
          childAspectRatio: 0.8 / 0.8,
          children: controller.tempList.map((item) => _hotItem(item)).toList(),
        ));
  }

  void _getMerchant(channel_id) {
    Map map = {
      "channel_id": channel_id,
    };
    print('channel_id=='+channel_id.toString());
    DioManager.getInstance().post(ServiceUrl.merchantList, map, (data) async {
      MerchantEntity bannerEntity = MerchantEntity.fromJson(jsonDecode(data));

      showDialog(context: context, builder: (BuildContext context1) {
        return MerchantDialog(merchantEntity:bannerEntity.data[0],callBack: (String content) {
            if(content=='close'){
              Navigator.pop(context1);
            }
        },
        );
      });
    }, (error) {
      ToastUtil.show(error);
    });
  }


  Widget _hotItem(GameListData item) {
    return InkWell(
      onTap: (){
        if(Constant.clcikSellTab){
          // Get.to(()=>SellPage(),arguments: item);
          if(Constant.tabFirst){
            Get.to(()=>SellPage(),arguments: {
              'channel_id':'',
              'channel_name':item.code,
              'title':item.name
            },preventDuplicates:false);
          }else{

             _getMerchant(item.code);

          }

        }else{
          Get.to(()=>BuyResultPage(),arguments: {
            'keyword':"",
            'channel_name':item.code,
            'name':item.name,
            'channel_id':item.id
          },preventDuplicates:false);
        }
      },
      child: Container(
          alignment: Alignment.center,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(16.r),
                ),
                alignment: Alignment.center,
                child: CachedNetworkImage(
                  imageUrl:    item.backimg,
                    imageBuilder: (context, imageProvider) => Container(
                        width: 50.w,
                        height: 50.w,
                        decoration: BoxDecoration(
                          image: DecorationImage(
                            image: imageProvider,
                            fit: BoxFit.cover,
                          ),
                        ))
                ),
              ),
              SizedBox(
                height: 3.h,
              ),
              Text(
                item.name.toString(),
                style: TextStyle(
                  color: Color(0xFF333333),
                  fontSize: 12.sp,
                ),
                textAlign: TextAlign.center,
              )
            ],
          ))
    ) ;
  }
}
